<template>
  <div class="homework-analysis anchor-offset" id="Homework-quality">
    <h3 class="scoreStateTitle">作业分析</h3>
    <!-- 2.3.1 作业质量 -->
    <div class="homework-quality">
      <h3 class="header-with-select">作业质量</h3>
      <el-card v-loading="loading">
        <div class="quality-overview">
          <ul>
            <li>
              满分
              <span>
                <i>{{ qualityData.fullScore }}</i>/分
              </span>
            </li>
            <li>
              人数
              <span>
                <i>{{ qualityData.submitCount }}</i>/人
              </span>
            </li>
            <li>
              难度
              <span>
                <i>{{ qualityData.difficulty }}</i>
              </span>
            </li>
            <li>
              区分度
              <span>
                <i>{{ qualityData.discrimination }}</i>
              </span>
            </li>
          </ul>
        </div>
        <el-table :data="evaluations || []" border stripe
          :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
          tooltip-effect="dark" style="width: 100%">
          <el-table-column prop="indicator" label="指标" align="center" width="120" />
          <el-table-column prop="paperEvaluation" label="整卷评价" align="center" />
          <el-table-column label="试题" align="center">
            <!-- prop="questionEvaluation" -->
            <template #default="scope">
              <span v-html="scope.row.questionEvaluation"
                style="text-align: left;display: inline-block;padding:5px 10px;"></span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
	  <div id="Test-score-rate" class="anchor-offset">
		  <h3 class="header-with-select" style="margin-top:24px;">试题得分率</h3>
		  <el-card v-loading="loading">
		    <el-table
		      :data="scoreRatesData"
		      border
		      stripe
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%"
		    >
				<el-table-column prop="name" label="全体/班级" align="center" >
					<!-- <template  slot-scope="scope">
						{{scope.row.type==0?'全体':'班级'}}
					</template> -->
				</el-table-column>
				<el-table-column
					v-for="(scored, index) in scoreRatesData[0].questionList"
					:key="index"
					:label="`${scored.questionNum}`"
					>
					<template #default="{ row }">
					<!-- 计算当前行的总人数 -->
					{{ row.questionList[index].scoreRate }}%
					</template>
				</el-table-column>
		    </el-table>
		  </el-card>
	  </div>
	  <div id="Test-knowledge-rate" class="anchor-offset">
		  <h3 class="header-with-select" style="margin-top:24px;">知识点得分率</h3>
		  <el-card v-loading="loading">
		    <el-table
		      :data="knowledgeRatesData"
		      border
		      stripe
			  :height="knowledgeRatesData.length > 10 ? '650px' : undefined"
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%"
		    >
				<el-table-column  label="" align="center" >
					<template  slot-scope="scope">
						{{scope.row.knowledge}}
					</template>
				</el-table-column>
				<el-table-column label="试题">
					<template slot-scope="scope">
						<span v-for="(item,chilindex) in scope.row.questionNums">
							题目:{{ item}}{{ scope.row.questionNums.length-1==chilindex?'':'、' }}
							<!-- {{ item.type }} -->
							<!-- <i v-for="(num,chipindex) in item.numbers">{{ item.type }}{{num}}{{ item.numbers.length-1==chipindex?'':'/' }}</i> -->
						</span>
					</template>
				</el-table-column>
				<el-table-column  label="得分率" align="center" >
					<template  slot-scope="scope">
						{{scope.row.scoreRate}}%
					</template>
				</el-table-column>
		    </el-table>
		  </el-card>
	  </div>
	  <div id="Small-question-analysis" class="anchor-offset">
		  <h3 class="header-with-select" style="margin-top:24px;">小题分析</h3>
		  <el-card v-loading="loading">
		    <div ref="questionAnalysisChart" style="width: 100%; height: 400px"></div>
		  </el-card>
	  </div>
	  <!-- <div id="Objective-Question-Answering">
		  <h3 class="header-with-select" style="margin-top:24px;">客观题作答分布</h3>
		  <el-card v-loading="loading">
		    <el-table :data="objectiveAnswerData" border stripe
			:height="objectiveAnswerData.length > 5 ? '504px' : undefined"
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%">
		      <el-table-column prop="questionNum" label="试题" align="center" />
		      <el-table-column prop="answer" label="答案" align="center" />
		      <el-table-column prop="score" label="分值" align="center" />
		      <el-table-column prop="avgScore" label="平均分" align="center" />
		      <el-table-column prop="scoreRate" label="得分率(%)" align="center" />
		      <el-table-column prop="fullScoreRate" label="满分率(%)" align="center" />
		      <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" />
		      <el-table-column label="学生作答" align="center" width="400">
		  			    <template slot-scope="scope">
		  					<ul class="studentanswer">
		  						<li v-for="option in scope.row.newstudentAnswer" :class="{'hover': isHighestPercentage(scope.row, option)}">{{option}}</li>
		  					</ul>
		  			    </template>
		  		  </el-table-column>
		    </el-table>
		  </el-card>
	  </div>
	  <div id="subjective-Question-Answering">
		  <h3 class="header-with-select" style="margin-top:24px;">主观题作答分布</h3>
		  <el-card v-loading="loading">
		    <el-table :data="subjectiveAnswerData" border stripe
			:height="subjectiveAnswerData.length > 5 ? '504px' : undefined"
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%">
		      <el-table-column prop="questionNum" label="试题" align="center" />
		      <el-table-column prop="answer" label="答案" align="center" />
		      <el-table-column prop="score" label="分值" align="center" />
		      <el-table-column prop="avgScore" label="平均分" align="center" />
		      <el-table-column prop="scoreRate" label="得分率(%)" align="center" />
		      <el-table-column prop="fullScoreRate" label="满分率(%)" align="center" />
		      <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" />
		      <el-table-column label="学生作答" align="center" width="500">
		  			  <template slot-scope="scope">
		  				<ul class="studentanswer">
		  					<li v-for="(option,cindex) in scope.row.newstudentAnswer" :class="{'hover': isHighestPercentage1(scope.row, option)}">{{option}}</li>
		  				</ul>
		  			  </template>
		  		  </el-table-column>
		    </el-table>
		  </el-card>
	  </div> -->
	   <div id="Distribution-Wrong-Questions" class="anchor-offset">
		   <h3 class="header-with-select" style="margin-top:24px;">错题分布</h3>
		   <error-distribution
		     :exam-id="examId"
		     :class-id="classId"
		   />
	   </div>
	   <div id="two-way-checklist" class="anchor-offset">
		   <h3 class="header-with-select" style="margin-top:24px;">多维细目表</h3>
		   <el-card v-loading="loading">
		     <el-table :data="matrixData" border stripe
			 :height="matrixData.length > 5 ? '504px' : undefined"
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%">
		       <el-table-column prop="type" label="题型" align="center" width="120" />
		       <el-table-column prop="number" label="题号" align="center" width="130" />
		       <el-table-column prop="score" label="分值" align="center" width="80" />
		       <el-table-column label="知识点" align="center">
		         <template #default="scope">
					<span v-if="scope.row.knowledge === '待补充'" class="pending-data">
		             {{ scope.row.knowledge }}
		           </span>
					<div class="expandable-cell" style="width:100%;" v-else>
						<Expandable :text="scope.row.knowledge"></Expandable>
					</div>
		         </template>
		       </el-table-column>
		       <el-table-column prop="difficulty" label="难度" align="center" width="100">
		         <template #default="scope">
					 <span class="tabbox" :class="getDifficultyClass(scope.row.difficulty)">{{scope.row.difficulty }}</span>
		         </template>
		       </el-table-column>
		     </el-table>
		   </el-card>
	   </div>
    </div>

  </div>
</template>

<script>
import {
  getHomeworkQuality,
  getQuestionScoreRates,
  getQuestionAnalysis,
  getObjectiveAnswerDistribution,
  getSubjectiveAnswerDistribution,
  getErrorDistribution,
  getQuestionMatrix,
  getKnowlegeScoreRates
} from '@/api/score'
import * as echarts from 'echarts'
import ErrorDistribution from './ErrorDistribution.vue'
import HomeworkSummary from './HomeworkSummary.vue'
import Expandable from '@/components/expandable.vue';
export default {
  name: 'HomeworkAnalysis',
  components: {
    ErrorDistribution,
    HomeworkSummary,
	Expandable
  },
  props: {
    examId: {
      type: [String, Number],
      required: true
    },
    classId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      qualityData: {
        fullScore: 0,
        submitCount: 0,
        difficulty: 0,
        discrimination: 0,
        evaluations: []
      },
      matrixData: [],
      scoreRatesData: [],
      questionAnalysisData: [],
      objectiveAnswerData: [],
      subjectiveAnswerData: [],
      loading: false,
      questionAnalysisChart: null,
      hasLoaded: false,
      loadingPromise: null,
      knowledgeRatesData: []
    }
  },
  methods: {
	toggleExpand(row) {
      this.$set(row, 'expanded', !row.expanded);
    },
	  getDifficultyClass(difficulty) {
	        switch (difficulty) {
	          case '简单':
	            return 'green';
	          case '较易':
	            return 'zs';
	          case '一般':
	            return 'blue';
	          case '困难':
	            return 'yellow';
	          default:
	            return 'red';
	        }
	      },
    async loadData() {
      if (this.loadingPromise) {
        return this.loadingPromise;
      }

      if (this.hasLoaded && this.subjectiveAnswerData.length > 0) {
        return;
      }

      try {
        this.loading = true;
        this.loadingPromise = Promise.all([
          getHomeworkQuality(this.examId, this.classId),
          getQuestionScoreRates(this.examId, this.classId),
          getQuestionAnalysis(this.examId, this.classId),
          getObjectiveAnswerDistribution(this.examId, this.classId),
          getSubjectiveAnswerDistribution(this.examId, this.classId),
          getKnowlegeScoreRates(this.examId, this.classId)
        ]);

        const [qualityRes, ratesRes, analysisRes, objectiveRes, subjectiveRes, knowledgeRes] = await this.loadingPromise;

        console.log('API responses:', {
          quality: qualityRes,
          rates: ratesRes,
          analysis: analysisRes
        });

        if (qualityRes.code === 200) {
          this.qualityData = qualityRes.data
          if (this.qualityData.discrimination > 1) {
            this.qualityData.discrimination = (Number(this.qualityData.discrimination) - Math.floor(Number(this.qualityData.discrimination))).toFixed(2)
          }
          const filteredEvaluations = qualityRes.data.evaluations.filter(item => item.indicator !== "信度");
          this.evaluations = filteredEvaluations.map(item => {
            if (item.questionEvaluation) {
              item.questionEvaluation = item.questionEvaluation
                .replace(/\([^)]*\)/g, '')
                .replace(/;/g, '<br />');
            }
            return item;
          });
        }

        if (ratesRes.code === 200) {
          this.scoreRatesData = ratesRes.data;
        }

        if (analysisRes.code === 200) {
          this.$nextTick(() => {
            this.initQuestionAnalysisChart(analysisRes.data);
          })
          //   this.initQuestionAnalysisChart(analysisRes.data);
        }

        if (objectiveRes.code === 200) {
          this.objectiveAnswerData = objectiveRes.data.map(item => ({
            ...item,
            newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
          }));
        }

        if (subjectiveRes.code === 200) {
          this.subjectiveAnswerData = subjectiveRes.data.map(item => ({
            ...item,
            newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
          }));
        }

        if (knowledgeRes.code === 200) {
          this.knowledgeRatesData = knowledgeRes.data;
          console.info(' this.knowledgeRatesData', this.knowledgeRatesData)
        }


        await this.loadMatrixData();
        this.hasLoaded = true;

      } catch (error) {
        console.error('加载作业分析数据失败:', error);
        this.$emit('load-error', error);
      } finally {
        this.loading = false;
        this.loadingPromise = null;
      }
    },
    handleResize () {
      if (this.questionAnalysisChart) {
        this.questionAnalysisChart.resize();
      }
    },
    initQuestionAnalysisChart (data) {
      console.log('Initializing chart with data:', data);

      // 检查 DOM 元素是否存在
      if (!this.$refs.questionAnalysisChart) {
        console.warn('Chart ref not found');
        return;
      }

      // 初始化 ECharts 实例
      if (!this.questionAnalysisChart) {
        this.questionAnalysisChart = echarts.init(this.$refs.questionAnalysisChart);
      }

      // 防御性代码：确保 data 存在且结构正确
      const questionList = data && data.length > 0 && data[0].questionList ? data[0].questionList : [];
      const questionList1 = data && data.length > 1 && data[1].questionList ? data[1].questionList : [];

      // 生成 xAxis 数据
      const xAxisData = questionList.map(item => `${item.questionNum}`);

      // 定义系列数据
      const series = [
        {
          name: '全体得分率',
          data: questionList.map(item => parseFloat(item.scoreRate)),
          color: '#295CFF', // 全体得分率颜色
        },
        {
          name: '班级得分率',
          data: questionList1.map(item => parseFloat(item.scoreRate)),
          color: '#29CE67', // 班级得分率颜色
        }
      ];

      // 动态生成 series 配置
      const seriesConfig = series.map(item => ({
        name: item.name,
        type: 'line',
        data: item.data,
        smooth: false,
        lineStyle: {
          color: item.color,
          width: 2,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(
            0, 1, 0, 0,
            [
              { offset: 1, color: item.color },
              { offset: 0.2, color: '#fff' },
              { offset: 0, color: '#fff' }
            ]
          ),
          opacity: 0.5,
        },
      }));

      // ECharts 配置项
      const option = {
        tooltip: {
          trigger: 'axis', // 触发类型为坐标轴
          formatter: (params) => {
            // params 是一个数组，包含当前鼠标所在位置的所有系列的数据
            let tooltipContent = `${params[0].name}<br/>`; // 显示题目编号
            params.forEach((item) => {
              tooltipContent += `${item.marker} ${item.seriesName}: ${item.value}%<br/>`; // 显示系列名称和值
            });
            return tooltipContent;
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
        },
        yAxis: {
          type: 'value',
          name: '得分率(%)',
          min: 0,
          max: 100,
          interval: 20,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#cccccc',
            },
          },
        },
        series: seriesConfig, // 动态生成的 series
      };

      // 设置图表配置
      this.questionAnalysisChart.setOption(option);
    },
    getDifficultyType (difficulty) {
      switch (difficulty) {
        case '容易': return 'success';
        case '中等': return 'warning';
        case '困难': return 'danger';
        default: return 'info';
      }
    },
    async loadMatrixData () {
      try {
        const res = await getQuestionMatrix(this.examId, this.classId);
        if (res.code === 200) {
          this.matrixData = res.data;
        }
      } catch (error) {
        console.error('加载双向细目表失败:', error);
      }
    },
    isHighestPercentage (row, option) {
      const options = row.newstudentAnswer;
      const correctAnswer = row.answer;

      // 提取每个选项的百分比
      const percentages = options.map(opt => {
        const match = opt.match(/\((\d+\.\d+)%\)/);
        return match ? parseFloat(match[1]) : 0;
      });

      // 找出与正确答案不同的选项
      const incorrectOptions = options.filter(opt => !opt.includes(correctAnswer));

      // 找出占比最高的选项
      const maxPercentage = Math.max(...percentages);

      // 判断当前选项是否是占比最高的且不是正确答案
      return option.includes(correctAnswer) ? false : percentages[options.indexOf(option)] === maxPercentage;
    },
    isHighestPercentage1 (row, option) {
      const options = row.newstudentAnswer;

      // 提取每个选项的百分比
      const percentages = options.map(opt => {
        const match = opt.match(/\((\d+\.\d+)%\)/);
        return match ? parseFloat(match[1]) : 0;
      });


      // 找出占比最高的选项
      const maxPercentage = Math.max(...percentages);

      // 判断当前选项是否是占比最高的且不是正确答案
      return percentages[options.indexOf(option)] === maxPercentage;
    }
  },
  watch: {
    examId (newVal) {
      if (newVal && this.classId && !this.hasLoaded) {
        this.loadData();
      }
    },
    classId (newVal) {
      if (newVal && this.examId && !this.hasLoaded) {
        this.loadData();
      }
    }
  },
  mounted () {
    console.log('HomeworkAnalysis mounted');
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.handleResize);
    if (this.questionAnalysisChart) {
      this.questionAnalysisChart.dispose();
    }
  },
  created () {
    console.log('HomeworkAnalysis created with props:', {
      examId: this.examId,
      classId: this.classId
    });
  }
}
</script>

<style scoped>
.homework-quality {
  background: #FFFFFF;
  box-shadow: 0 4px 16px 0 #5572921a;
  border-radius: 10px;
  padding: 24px;
}

.quality-overview {
  margin-bottom: 20px;
}

.quality-overview ul {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
}

.quality-overview ul li {
  box-sizing: border-box;
  height: 78px;
  border-radius: 10px;
  padding: 0 14px;
  flex: 1;
  font-size: 16px;
  padding-top: 10px;
}

.quality-overview ul li span {
  display: block;
  font-size: 16px;
  font-style: normal;
  color: #B3B8C2;
  padding-top: 2px;
}

.quality-overview ul li span i {
  font-style: normal;
  font-size: 24px;
  font-weight: bold;
}

.quality-overview ul li:nth-child(1) {
  background: rgb(247, 249, 255);
  border: solid 1px rgb(231, 236, 255)
}

.quality-overview ul li:nth-child(1) span i,
.quality-overview ul li:nth-child(2) span i {
  color: #295CFF
}

.quality-overview ul li:nth-child(2) {
  background: rgb(254, 248, 249);
  border: solid 1px rgb(252, 235, 236)
}

.quality-overview ul li:nth-child(3) {
  background: rgb(253, 251, 247);
  border: solid 1px rgb(249, 243, 231)
}

.quality-overview ul li:nth-child(4) {
  background: rgb(247, 251, 248);
  border: solid 1px rgb(230, 242, 233)
}

.quality-overview ul li:nth-child(3) span i,
.quality-overview ul li:nth-child(4) span i {
  color: #2A303B
}

.header-with-select {
  font-size: 16px;
  color: #2A303B;
  margin-bottom: 14px;
}

.pending-data {
  color: #909399;
  font-style: italic;
}

.question-matrix {
  margin-top: 20px;
}

.scoreStateTitle {
  font-size: 18px;
  color: #295CFF;
  line-height: 45px;
  font-weight: normal;
  position: relative;
  padding-left: 25px;
  font-weight: bold
}

.scoreStateTitle:after {
  content: '';
  width: 14px;
  height: 14px;
  opacity: 0.5;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 0;
  top: 15px;
}

.scoreStateTitle::before {
  content: '';
  width: 8px;
  height: 8px;
  opacity: 0.2;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 10px;
  top: 23px;
}

.custom-table {
  width: 100%;
  border: 1px solid rgba(216, 228, 240, 1);
  border-radius: 10px;
  border-right: none;
  border-bottom: none;
  margin-top: 0;
}

/* 自定义表格内部元素的样式 */
.custom-table>>>.el-table__header-wrapper th {
  background-color: rgb(232, 240, 250);
  height: 42px;
  padding: 0;
  text-align: center;
  font-weight: normal
}

.custom-table>>>.el-table__row td {
  height: 42px;
  padding: 0;
  text-align: center;
  border-bottom: none;
  border-right: solid 1px rgba(216, 228, 240, 1);
}

.el-table .warning-row {
  background: #ffffff;
}

.el-table .success-row {
  background: #D8E4F0;
}

.el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover,
.el-cascader__dropdown,
.el-color-picker__panel,
.el-message-box,
.el-notification {
  box-shadow: none;
}

.homework-quality>>>.el-card__body,
.homework-quality>>>.el-main {
  padding: 0 !important;
}

.homework-quality>>>.el-card {
  border: none;
}
.tabbox{
	display: inline-block;
	width: 60px;
	height: 22px;
	border-radius: 10px;
}

.green {
  background: rgb(225, 248, 233);
  border: 1px solid #29CE67;
  color: #29CE67;
}

.zs {
  background: rgb(242, 236, 255);
  border: 1px solid rgb(224, 209, 255);
  color: #A777FF;
}

.blue {
  background: rgb(229, 238, 255);
  border: 1px solid rgb(167, 196, 254);
  color: #4985FF
}

.yellow {
  background: rgb(255, 243, 236);
  border: 1px solid rgb(255, 211, 181);
  color: #FFAB77;
}

.red {
  background: rgb(255, 236, 236);
  border: 1px solid rgb(255, 189, 189);
  color: #FF7777;
}
.expandable-cell {
  position: relative;
}
.content1 {
  cursor: pointer;
}
.content1.collapsed {
  display: -webkit-box;
  -webkit-line-clamp: 1; /* 限制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
.anchor-offset {
  scroll-margin-top: 60px;
}
</style>
